package com.nulldev.util.uri.server.legacy;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;

import com.nulldev.util.internal.JDKSupportManager;
import com.nulldev.util.internal.UnsupportedFromJDK;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.uri.http.HTTP;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

@Deprecated
public class HTTPServer{
	private Logger logger = LoggerFactory.getLogger();
	private HttpServer server;

	public HTTPServer(final InetSocketAddress addr) throws IOException {
		this(addr, null);
	}

	@UnsupportedFromJDK(maxSupportedJDK = 1.8)
	public HTTPServer(final InetSocketAddress addr, final ExecutorService service) throws IOException {
		JDKSupportManager.createCall();
		this.logger.infoEnabled = true;
		this.server = HttpServer.create(addr, 0);
		if (this.server == null) {
			this.server.setExecutor(null);
		}else {
			this.server.setExecutor(service);
		}
		this.server.start();
	}

	public void stop() {
		this.stop(0);
	}

	public void stop(final int arg) {
		if (this.server == null) {
			throw new RuntimeException("stop(): this.server is null.");
		}
		this.server.stop(arg);
	}

	public void createContext(final String dta, final HttpHandler res) {
		if (this.server == null) {
			throw new RuntimeException("createContext(arg0, arg1): this.server is null.");
		}
		this.server.createContext(dta, res);
	}

	public void defaultContext() {
		this.createContext("/", new HttpHandler() {

			@Override
			public void handle(HttpExchange arg0) throws IOException {
		        final String response = "<html><head><h2>nullUtil: HTTPServer Test</h2></head></html>";
		        arg0.sendResponseHeaders(HTTP.OK, response.getBytes().length);
		        final OutputStream os = arg0.getResponseBody();
		        os.write(response.getBytes());
		        os.close();
			}
		});
		logger.info("Context created. You can connect to me using 'http://" + this.server.getAddress().getAddress().getHostAddress() + ":" + this.server.getAddress().getPort() + "/'.");
	}
}
